import React, { useState, useEffect } from 'react';
import { Tree, Menu, Message } from 'antd';
import APIS from '@/api/cyindex.js';
import API from '@/api/xjindex.js';
import { useModel } from 'umi';
import Check from './_index';

// 单位运营管理   0未点击 1查看  2新增
const operationManagement = () => {
  const { initialState } = useModel('@@initialState');
  const { userId, orgId } = initialState.info;
  const [orgList, setOrgList] = useState([]);
  const [initList, setInitList] = useState({});
  const [menus, setMenus] = useState({
    key: '',
    state: 0,
  });
  const digui = (arrs) => {
    const result = arrs.map((arr) => {
      return {
        title: arr.name,
        key: arr.id,
        children: arr.children && digui(arr.children),
      };
    });
    return result;
  };
  const init = () => {
    APIS.getAllOrg().then((res) => {
      if (res) {
        setOrgList(
          res.t.map((item) => {
            return {
              title: item.name,
              key: item.id,
              children: item.children && digui(item.children),
            };
          }),
        );
      }
    });
  };
  const onRightClick = (keys) => {
    if (keys[0]) {
      const key = keys[0];
      API.getUnitManagemenetById({ id: key }).then((res) => {
        if (res) {
          setInitList({ ...res.t });
          if (res.t) {
            setMenus({ key, state: 1 });
          } else {
            if (orgId === key) {
              Message.info('暂无信息，请先新增');
              setMenus({ key: key, state: 2 });
            } else {
              Message.warning('暂无信息，请联系该单位人员新增组织架构');
              setMenus({ key: key, state: -1 });
            }
          }
        }
      });
    }
  };

  useEffect(() => {
    init();
  }, []);

  return (
    <>
      <div className="main-x  assets_menu">
        <div
          style={{
            width: '20%',
            height: '100%',
            marginRight: '10px',
            overflow: 'auto',
          }}
        >
          <Tree
            treeData={orgList}
            style={{
              borderRadius: 8,
              padding: 6,
            }}
            onSelect={onRightClick}
          ></Tree>
        </div>
        <div style={{ width: '80%', overflow: 'auto' }}>
          {menus.state > 0 ? (
            <Check initList={initList} menus={menus}></Check>
          ) : null}
        </div>
      </div>
    </>
  );
};

export default operationManagement;
